#include <atspi/atspi.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <unistd.h>
#include <glib-unix.h>

// 添加全局退出标志
static volatile sig_atomic_t exiting = 0;

// 事件处理函数
static void focus_event_callback(AtspiEvent *event, void *user_data)
{
    if (exiting)
        return;

    const char *name = NULL;
    const char *role_name = "Unknown";
    GError *error = NULL;
    gchar *text_content = NULL;

    if (event && event->source)
    {

        // 获取组件名称和角色
        name = atspi_accessible_get_name(event->source, &error);
        if (error)
        {
            fprintf(stderr, "Error getting name: %s\n", error->message);
            g_error_free(error);
            error = NULL;
        }

        AtspiRole role = atspi_accessible_get_role(event->source, &error);
        if (!error)
        {
            role_name = atspi_role_get_name(role);
        }
        else
        {
            fprintf(stderr, "Error getting role: %s\n", error->message);
            g_error_free(error);
            error = NULL;
        }

        printf("Focus Event: %s (%s)\n", name ? name : "NONAME", role_name);

        // 检查是否为文本输入类型组件
        if (role == ATSPI_ROLE_TEXT || role == ATSPI_ROLE_ENTRY ||
            role == ATSPI_ROLE_PASSWORD_TEXT || role == ATSPI_ROLE_DOCUMENT_TEXT)
        {

            // 获取Text接口
            AtspiText *text_interface = atspi_accessible_get_text_iface(event->source);
            if (!text_interface)
            {
                fprintf(stderr, "Failed to get Text interface\n");
                goto cleanup;
            }

            // 获取完整文本内容 (0到-1表示整个文本范围)
            text_content = atspi_text_get_text(text_interface, 0, -1, &error);

            if (error)
            {
                fprintf(stderr, "Error getting text: %s\n", error->message);
                g_error_free(error);
                error = NULL;
            }
            else if (text_content)
            {
                printf("Text Content: %s\n", text_content);
            }

            // 释放接口引用
            g_object_unref(text_interface);
        }
    }

cleanup:
    if (name)
        g_free((gpointer)name);
    if (text_content)
        g_free(text_content);
}

// 信号处理函数
static gboolean handle_signal(gpointer user_data)
{
    exiting = 1;
    GMainLoop *loop = (GMainLoop *)user_data;
    g_main_loop_quit(loop);
    return FALSE;
}

int main()
{
    // 初始化 AT-SPI
    if (atspi_init() != 0)
    {
        fprintf(stderr, "AT-SPI initialization failed\n");
        return 1;
    }

    // 创建事件监听器
    GError *error = NULL;
    AtspiEventListener *listener = atspi_event_listener_new(
        (AtspiEventListenerCB)focus_event_callback,
        NULL, // 用户数据
        NULL  // 错误回调
    );

    if (!listener)
    {
        fprintf(stderr, "Failed to create event listener\n");
        atspi_exit();
        return 1;
    }

    // 注册焦点事件监听
    gboolean registered = atspi_event_listener_register(
        listener,
        "object:state-changed:focused",
        &error);

    if (error)
    {
        fprintf(stderr, "Error registering listener: %s\n", error->message);
        g_error_free(error);
        g_object_unref(listener);
        atspi_exit();
        return 1;
    }

    // 创建主事件循环
    GMainLoop *loop = g_main_loop_new(NULL, FALSE);
    g_unix_signal_add(SIGINT, handle_signal, loop);
    printf("Listening for text input focus. Press Ctrl+C to exit...\n");
    g_main_loop_run(loop);

    // 清理
    atspi_event_listener_deregister(listener, "object:state-changed:focused", NULL);
    g_object_unref(listener);
    g_main_loop_unref(loop);
    atspi_exit();

    return 0;
}